<template>
  <div class="app-container customer-div">
    <el-tabs v-model="activeName">
      <el-tab-pane label="消息模板设置" name="first">
        <div style="margin-top: 20px">
          <!--搜索-->
          <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
            <el-form-item label="消息名称：">
              <el-input v-model="listQuery.templateName"></el-input>
            </el-form-item>
            <el-form-item label="类型：" >
              <el-select v-model="listQuery.templateType" clearable >
                 <el-option label="文本卡片" value="textCard"></el-option>
                 <el-option label="文本" value="text"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="应用：">
              <el-select v-model="listQuery.templateApp" clearable>
                <el-option label="销售" value="销售"></el-option>
                <el-option label="采购" value="采购"></el-option>
                <el-option label="仓库" value="仓库"></el-option>
                <el-option label="财务" value="财务"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleSearchList()"
                type="primary">
                查询
              </el-button>
              <el-button
                :loading="btnLoading2"
                @click="showPop('add','')"
                type="primary">
                新增模版
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <el-table
            size="mini"
            v-loading="loading"
            :data="list"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column
              min-width="100"
              label="消息名称"
              align="center">
              <template slot-scope="scope">{{scope.row.templateName}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="消息类型"
              align="center">
              <template slot-scope="scope">{{scope.row.templateType == 'text' ? '文本' : '卡片'}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="应用"
              align="center">
              <template slot-scope="scope">{{scope.row.templateApp}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="消息频次"
              align="center">
              <template slot-scope="scope">{{scope.row.sendType}}</template>
            </el-table-column>
            <el-table-column
              min-width="150"
              show-overflow-tooltip
              label="消息模板"
              align="center">
              <template slot-scope="scope">{{scope.row.templateCode}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="接收人"
              align="center">
              <template slot-scope="scope">{{scope.row.receiveName}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="备注"
              show-overflow-tooltip
              align="center">
              <template slot-scope="scope">{{scope.row.templateRemark}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="状态"
              align="center">
              <template slot-scope="scope">{{scope.row.templateState | fifState}}</template>
            </el-table-column>
            <el-table-column
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="showPop('edit',scope.row)" size="mini">编辑</el-button>
                <el-button type="text" v-if="scope.row.templateState === 0" @click="changStatus(10,scope.row)"  size="mini">禁用</el-button>
                <el-button type="text" v-else-if="scope.row.templateState === 10" @click="changStatus(0,scope.row)"  size="mini">启用</el-button>
              </template>
            </el-table-column>

          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery.pageNum"
            :page-size="listQuery.pageSize"
            :page-sizes="[10,15,20]"
            :total="count">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="消息记录" name="second">
        <div style="margin-top: 20px">
          <!--搜索-->
          <el-form :inline="true" :model="listQuery2" size="mini" label-width="100px">
            <el-form-item label="发送时间：">
              <el-date-picker
                v-model="listQuery2.timeDate"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="接收人：">
              <el-select v-model="listQuery2.userName" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in userOptionList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="listQuery2.recordState" clearable>
                <el-option label="未发送" value="0"></el-option>
                <el-option label="已发送" value="1"></el-option>
                <el-option label="发送失败" value="2"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                @click="handleSearchList2()"
                type="primary">
                查询
              </el-button>

              <el-button
                @click="delBatch('more','')"
                type="primary">
                批量删除
              </el-button>

            </el-form-item>
          </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <el-table
            size="mini"
            v-loading="loading2"
            :data="list2"
            row-key="deliverId"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column type="selection" :reserve-selection="true" width="60" align="center"></el-table-column>
            <el-table-column
              min-width="150"
              label="发送时间"
              align="center">
              <template slot-scope="scope">{{scope.row.createdTime}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="接收人"
              align="center">
              <template slot-scope="scope">{{scope.row.receiverNames}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="类型"
              align="center">
              <template slot-scope="scope">{{scope.row.templateApp}}</template>
            </el-table-column>
            <el-table-column
              min-width="100"
              label="消息名称"
              align="center">
              <template slot-scope="scope">{{scope.row.templateName}}</template>
            </el-table-column>
            <el-table-column
              min-width="200"
              label="消息内容" header-align="center">
              <template slot-scope="scope">{{scope.row.recordContent}}</template>
            </el-table-column>

            <el-table-column
              min-width="100"
              label="状态"
              align="center">
              <template slot-scope="scope">{{scope.row.recordState | fifrecordState}}</template>
            </el-table-column>
            <el-table-column
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="delBatch('one',scope.row)" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery2.pageNum"
            :page-size="listQuery2.pageSize"
            :page-sizes="[10,15,20,100,200]"
            :total="count2">
          </el-pagination>
        </div>

      </el-tab-pane>
    </el-tabs>

    <!--新增/编辑模版--->
    <el-dialog
      :close-on-click-modal="false"
      title="模板设置"
      :beforeClose="handleClose"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form :model="form" size="mini" label-width="120px" :rules="rules" ref="form">
        <el-form-item label="消息名称：" prop="templateName">
            <el-input style="width:200px" v-model="form.templateName"></el-input>
        </el-form-item>
        <el-form-item label="消息类型：" prop="templateType">
            <el-radio-group v-model="form.templateType">
               <el-radio label="textCard">文本卡片</el-radio>
               <el-radio label="text">文本</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="应用：" prop="templateApp">
          <el-select v-model="form.templateApp">
            <el-option label="销售" value="销售"></el-option>
            <el-option label="采购" value="采购"></el-option>
            <el-option label="仓库" value="仓库"></el-option>
            <el-option label="财务" value="财务"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息频次：" prop="sendType">
          <el-row>
             <el-col :span="11">
               <el-radio-group v-model="form.sendType">
                 <el-radio label="single">按生成单次</el-radio>
                 <el-radio label="dayTime">按天多次</el-radio>
               </el-radio-group>
             </el-col>
            <el-col :span="13">
              <el-form-item label-width="0px" prop="sendTime" v-if="form.sendType == 'dayTime'">
                <el-select  style="margin-left:10px;" multiple v-model="form.sendTime">
                  <el-option v-for="(item,index) in timeList" :label="item" :value="item" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="选择模板：" prop="templateCode">
            <el-select v-model="form.templateCode">
              <el-option v-for="(item,index) in btns" :label="item.title" :value="item.code" :key="index"></el-option>
            </el-select>
        </el-form-item>

<!--        <el-form-item label="消息内容：" >-->
<!--          <el-input-->
<!--            ref="smsInput"-->
<!--            type="textarea"-->
<!--            :autosize="{ minRows: 6, maxRows: 10}"-->
<!--            v-model="smsContent"-->
<!--            placeholder="请输入内容"-->
<!--            @input.native="smsInput"-->
<!--            @blur="inputBlur"-->
<!--            @focus="focusHandler"-->
<!--            @click.native="focusHandler"-->
<!--            @keydown.up.down.left.right.native="focusHandler"-->
<!--            @select.native="selectHandler"-->
<!--          ></el-input>-->
<!--          <el-tag size="mini" v-for="(item,index) in btns" :key="index" @click="insertStr('['+item+']')" style="cursor: pointer;margin-right:5px">{{item}}</el-tag>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="链接地址：" >-->
<!--           <el-input></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="接收人：" >
            <el-checkbox-group v-model="form.receiveFieldsCodes">
                <el-checkbox v-for="item in checkList" :key="item.code" :label="item.code">{{item.title}}</el-checkbox>
            </el-checkbox-group>
            <el-select filterable placeholder="请选择" clearable multiple v-model="form.receiveUserIds">
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="接收部门">
          <el-cascader
            v-model="form.receiveDeparmentIds"
            :options="data2"
            :props="{ checkStrictly: true,value:'departmentId',label:'departmentName',emitPath:false,multiple:true}"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.templateRemark"
            ref="smsInput"
            type="textarea"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getDeptList,} from '@/api/management'
import { goodsProfitList,goodsProfitEdit,syncGoodsClass,getCustomerSetting,getOrderUsersList} from '@/api/partner'
import {templateList,templateCode,addTemplate,templateInfo,updateStatus,newLogList,wechatNewBatchDelete} from '@/api/company'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultListQuery = {
  templateName:'',
  templateType:'',
  templateApp:'',
  pageNum:1,
  pageSize:10,
};

const defaultListQuery2 = {
  timeDate:[],
  userName:'',
  recordState:'',
  pageNum:1,
  pageSize:10,
};

const defaultForm = {
  templateId:0,
  templateName:'',
  templateType:'',
  templateApp:'',
  templateCode:'',
  sendType:'',  //single 单次  ，sendTime  多次
  receiveUserIds:[],
  receiveFieldsCodes:[],
  receiveDeparmentIds:[],
  sendTime:[],
  templateRemark:'',
};

export default {
  name: "index",
  data(){
    return{
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery:JSON.parse(JSON.stringify(defaultListQuery)),
      form:JSON.parse(JSON.stringify(defaultForm)),
      list:[],
      count:0,
      loading:false,
      dialogVisible:false,
      btnLoading:false,
      rules:{
        templateName:[{required: true, trigger: 'blur' ,message: '此项必填'}],
        templateCode:[{required: true, trigger: 'change' ,message: '此项必填'}],
        templateType:[{required: true, trigger: 'change' ,message: '此项必填'}],
        templateApp:[{required: true, trigger: 'change' ,message: '此项必填'}],
        sendType:[{required: true, trigger: 'change' ,message: '此项必填'}],
        sendTime:[{required: true, trigger: 'change' ,message: '此项必填'}],
      },

      btnLoading2:false,
      goodsLineList:[],
      activeName:'first',

      userOptionList:[],
      goodsClassList:[],



      listQuery2:JSON.parse(JSON.stringify(defaultListQuery2)),
      list2:[],

      count2:0,
      loading2:false,
      popType:'',

      smsContent: "",
      inputFocus: null,
      btns:[],
      data2:[],
      timeList:[],
      selectList:[],
      checkList:[],
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),

  },
  created() {
    this.getList();
    this.getList2();
    this.getUserOptionList();
    this.getBuMenList();
    this.getTemplateCode();
    this.timeList = this.timeSlot(20)
  },
  filters: {
    fifState(val){
      if(val === 0){
        return '启用'
      }else if(val === 10){
        return  '禁用'
      }
    },
    fifrecordState(val){
      if(val === 0){
        return '未发送'
      }else if(val === 1){
        return  '已发送'
      }else if(val === 2){
        return  '发送失败'
      }
    },
  },
  methods:{
      changStatus(templateState,item){
        updateStatus({templateState:templateState, templateId:item. templateId}).then(()=>{
             this.getList();
            this.$message({
              message: '修改成功',
              type: 'success',
              duration:1000
            });
        })
      },
      //获取模板参数
      getTemplateCode(){
        templateCode({type:1}).then((res)=>{
           this.btns = res;
        })
        templateCode({type:2}).then((res)=>{
          this.checkList = res;
        })
      },
      delBatch(type,item){
        if(type == 'more' && this.selectList.length == 0){
          this.$message({
            message: '请先选择记录',
            type: 'info',
            duration:1000
          });
          return false
        }
        let recordId = [];
        if(type == 'more'){
          this.selectList.forEach((el)=>{
            recordId.push(el.recordId)
          })
        }else{
          recordId.push(item.recordId)
        }
        this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          wechatNewBatchDelete({recordId:recordId}).then((res)=>{
            this.$message({
              type: 'success',
              message: '已删除成功!'
            });
            this.selectList = [];
            this.$refs.multipleTable.clearSelection();
            this.getList2();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },

      //切换选择
      handleSelectionChange(val){
        this.selectList = JSON.parse(JSON.stringify(val));
      },


     //获取时间列表
     timeSlot (step) {   //  step = 间隔的分钟
        var date = new Date()
        date.setHours('00')    // 时分秒设置从零点开始
        date.setSeconds('00')
        date.setUTCMinutes('00')

        var timeArr = [];
        var slotNum = 24*60/step   // 算出多少个间隔
        for (var f = 0; f < slotNum; f++) {   //  stepM * f = 24H*60M
          var time = new Date(Number(date.getTime()) + Number(step*60*1000*f))  // 获取：零点的时间 + 每次递增的时间
          var hour = '', sec = '';
          time.getHours() < 10 ? hour = '0' + time.getHours() : hour = time.getHours()  // 获取小时
          time.getMinutes() < 10 ? sec = '0' + time.getMinutes() : sec = time.getMinutes()   // 获取分钟
          timeArr.push(hour + ':' + sec)
        }
        return timeArr
      },
    //获取部门列表
    getBuMenList(){
      this.dataLoading = true;
      getDeptList().then((res)=>{
        this.data = res;
        this.data2 = [];
        this.data2 = this.forTree(this.data);
        this.dataLoading = false;

      })
    },

    //去除不要的children
    forTree(list){
      let newList = list;
      if(newList.length){
        for (let i = 0; i<newList.length; i++){
          if(newList[i].children && newList[i].children.length > 0){
            this.forTree(newList[i].children)
          }else{
            delete newList[i].children;
          }
        }
        return newList
      }
    },

    // 插入元素
    insertStr(str) {
      let before = this.smsContent.slice(0, this.inputFocus);
      let after = this.smsContent.slice(
        this.inputFocus,
        this.smsContent.length
      );
      this.inputFocus = this.inputFocus + str.length;
      this.smsContent = before + str + after;
    },
    // 保存光标位置
    inputBlur(e) {
      this.inputFocus = e.target.selectionStart;
    },
    // 删除元素剩余部分
    smsInput(e) {
      //deleteContentBackward==退格键 deleteContentForward==del键
      console.log(e.inputType)
      if (
        e.inputType == "deleteContentBackward" ||
        e.inputType == "deleteContentForward"
      ) {
        let beforeIndex = 0;
        let afterIndex = 0;
        // 光标位置往前
        for (let i = e.target.selectionStart - 1; i >= 0; i--) {
          if (this.smsContent[i] == "[") {
            beforeIndex = i;
            afterIndex = e.target.selectionStart;
            break;
          }
          if (this.smsContent[i] == "]") {
            break;
          }
        }
        // 光标位置往后
        for (let i = e.target.selectionStart; i < this.smsContent.length; i++) {
          if (this.smsContent[i] == "]") {
            afterIndex = i+1;
            beforeIndex = e.target.selectionStart;
            break;
          }
          if (this.smsContent[i] == "[") {
            break;
          }
        }
        if(beforeIndex == 0 && afterIndex == 0){
          return
        }
        let beforeStr = this.smsContent.slice(0,beforeIndex)
        let afterStr = this.smsContent.slice(afterIndex)
        this.smsContent = beforeStr+afterStr
        this.inputFocus = beforeStr.length
        this.$nextTick(() => {
          this.changeFocus(e.target, this.inputFocus, this.inputFocus);
        });
      }
      // this.$emit("smsText", this.smsContent);
    },
    // 选择元素剩余部分
    selectHandler(e) {
      // 光标开始位置往前
      for (let i = e.target.selectionStart - 1; i >= 0; i--) {
        if (this.smsContent[i] == "[") {
          this.changeFocus(e.target, i, e.target.selectionEnd);
          break;
        }
        if (this.smsContent[i] == "]") {
          break;
        }
      }
      // 光标结束位置往后
      for (let i = e.target.selectionEnd; i < this.smsContent.length; i++) {
        if (this.smsContent[i] == "]") {
          this.changeFocus(e.target, e.target.selectionStart, i + 1);
          break;
        }
        if (this.smsContent[i] == "[") {
          break;
        }
      }
    },
    // 焦点跳出元素内
    focusHandler(e) {
      setTimeout(() => {
        let selStart = e.target.selectionStart
        let beforeArrLength = this.smsContent
          .slice(0, selStart)
          .split("[").length;
        let afterArrLength = this.smsContent
          .slice(0, selStart)
          .split("]").length;
        //根据'['和']'生成两个数组 判断数组长度 是否相等 不相等就不成对就移动光标
        if (beforeArrLength != afterArrLength) {
          let pos = this.smsContent.indexOf("]", selStart) + 1
          if(beforeArrLength > afterArrLength && e.code == 'ArrowLeft'){//按下按键左箭头
            pos = this.smsContent.lastIndexOf("[",selStart)
          }
          this.changeFocus(e.target,pos,pos);
        }
      }, 100);
    },
    // 修改光标位置
    changeFocus(target, start, end) {
      let range,
        el = target;
      if (el.setSelectionRange) {
        el.setSelectionRange(start, end);
      } else {
        range = el.createTextRange();
        range.collapse(false);
        range.select();
      }
    },



    getClassList(){
      goodsProfitList({ pageNum:1, pageSize:1000,}).then((res)=>{
        this.goodsClassList = res.list
      })
    },
    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
    },

    //显示弹窗
    showPop(type,item){
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm))
      if(type == 'edit'){
        templateInfo({templateId:item.templateId}).then((res)=>{
          this.form = JSON.parse(JSON.stringify(res));
          this.form.receiveUserIds = [];
          this.form.receiveDeparmentIds = [];
          res.receiveUserIds.forEach((el)=>{
            this.form.receiveUserIds.push(parseInt(el))
          })
          res.receiveDeparmentIds.forEach((el)=>{
            this.form.receiveDeparmentIds.push(parseInt(el))
          })
          console.log(this.form)
        })
      }
    },

    //关闭
    handleClose(){
      this.dialogVisible = false;
    },

    //提交
    handleConfirm(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.form));
          if(data.sendType != 'dayTime'){
              delete data.sendTime
          }
          this.btnLoading = true;
          addTemplate(data).then((res)=>{
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.btnLoading = false;
            this.getList();
            this.handleClose();
          }).catch(()=>{
            this.btnLoading = false
          })
        }
      })
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },
    //获取记录
    getList(){
      this.loading = true;
      templateList(this.listQuery).then((res)=>{
        this.list = res.list;
        this.count = res.count;
        this.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList2(){
      this.listQuery2.pageNum = 1;
      this.getList2();
    },
    //获取记录
    getList2(){
      this.loading2 = true;
      newLogList(this.listQuery2).then((res)=>{
        this.list2 = res.list;
        this.count2 = res.count;
        this.loading2 = false;
      }).catch(()=>{
        this.loading2 = false;
      })
    },

    handleSizeChange2(val){
      this.listQuery2.pageNum = 1;
      this.listQuery2.pageSize = val;
      this.getList2();
    },
    handleCurrentChange2(val){
      this.listQuery2.pageNum = val;
      this.getList2();
    },

  },
}
</script>

<style scoped lang="scss">

</style>
